import { createRouter, createWebHistory } from "vue-router";
import { defaultRouter } from "./modules/defaultRouter";
import { errorRouter } from "./modules/errorRouter";
import { notFoundRouter } from "./modules/notFoundRouter";

import { ElNotification } from "element-plus";
import NProgress from "@/plugins/nprogress";
import getPageTitle from "@/utils/get-page-title";
import { getToken, setToken } from "@/utils/auth";

import { AuthStore } from "@/stores/modules/auth";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...defaultRouter, ...errorRouter, notFoundRouter],
});

setToken("token-1234");

// 全局路由守卫
/**
 * @description 路由拦截 beforeEach
 * */
router.beforeEach(
  (to: any, _from: any, next: (arg0: string | undefined) => void) => {
    // 页面加载进度条
    NProgress.start();
    // 设置页面标题
    document.title = getPageTitle(to.meta.title);

    const store = AuthStore();
    // const configStore = useConfigStore();

    // configStore.setTopPath(to.meta.topPath);
    // store.dispatch("setTopPath", to.meta.topPath);
    const token = getToken() || localStorage.getItem("access_token"); //登录标示
    const login = store.login; //store登录状态

    if (to.meta.open == true) {
      next(undefined);
    } else {
      if (login && token) {
        next(undefined);
      } else {
        try {
          console.time("time");
          console.log("路由载入中...");
          store
            .updatePerms()
            .then(() => {
              console.log("路由载入完...");
              console.timeEnd("time");
              next({
                ...to,
                replace: true,
              }); // hack方法 确保addRoutes已完成
            })
            .catch((e) => {
              console.log(e);
              next("/account/login");
            });
          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
        } catch (error) {
          // remove token and go to login page to re-login
          next(`/account/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  }
);

/**
 * @description 路由跳转结束
 * */
router.afterEach(() => {
  NProgress.done();
});

/**
 * @description 路由跳转错误
 * */
router.onError((error) => {
  NProgress.done();
  ElNotification.error({ title: "路由错误", message: error.message });
});

export default router;
